// 只做 require，确保 dotenv、dbConfig、pool 创建等被覆盖
const db = require('../../config/database');

describe('database.js require 阶段', () => {
  test('should export pool, query, transaction, testConnection', () => {
    expect(db).toHaveProperty('pool');
    expect(db).toHaveProperty('query');
    expect(db).toHaveProperty('transaction');
    expect(db).toHaveProperty('testConnection');
    expect(typeof db.query).toBe('function');
    expect(typeof db.transaction).toBe('function');
    expect(typeof db.testConnection).toBe('function');
  });

  test('dbConfig 环境变量分支', () => {
    const OLD_ENV = { ...process.env };
    process.env.DB_HOST = 'testhost';
    process.env.DB_USER = 'testuser';
    process.env.DB_PASSWORD = 'testpass';
    process.env.DB_NAME = 'testdb';
    process.env.DB_PORT = '1234';
    jest.resetModules();
    const db2 = require('../../config/database');
    expect(db2).toBeDefined();
    process.env = OLD_ENV;
  });

  test('dotenv 路径异常', () => {
    jest.resetModules();
    jest.mock('path', () => ({ join: () => '/not/exist/path' }));
    const dotenvSpy = jest.spyOn(require('dotenv'), 'config').mockImplementation(() => ({ error: new Error('not found') }));
    expect(() => require('../../config/database')).not.toThrow();
    dotenvSpy.mockRestore();
    jest.resetModules();
  });

  test('mysql.createPool 抛错', () => {
    jest.resetModules();
    jest.mock('mysql2/promise', () => ({ createPool: () => { throw new Error('pool error'); } }));
    expect(() => require('../../config/database')).toThrow('pool error');
    jest.resetModules();
  });

  test('多次 require 缓存分支', () => {
    jest.resetModules();
    const db1 = require('../../config/database');
    const db2 = require('../../config/database');
    expect(db1).toBe(db2);
  });
}); 